<!-- 组织架构 -->
<template>
  <div class="container">
    <div class="app-container">
      <!-- data数据, props设置label属性契合接口返回的字段, 这里children跟接口的children一样, 所以不做修改 -->
      <el-tree :data="treeData" :props="{label: 'name'}" :expand-on-click-node="false" default-expand-all>
        <!-- 作用域插槽: data代表每一行数据, 相当于表格的作用域插槽{row} -->
        <template #default="{data}">
          <!-- el-row相当于鸿蒙的Row组件 -->
          <el-row :style="{width: '100%'}" type="flex" justify="space-between">
            <div>{{ data.name }}</div>
            <el-row :style="{width:'130px'}" type="flex" justify="space-between">
              <span>{{ data.managerName }}</span>
              <el-dropdown @command="command($event, data.id)">
                <span class="el-dropdown-link">
                  操作<i class="el-icon-arrow-down" />
                </span>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="add">添加子部门</el-dropdown-item>
                  <el-dropdown-item command="edit">编辑部门</el-dropdown-item>
                  <el-dropdown-item command="del">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>

            </el-row>
          </el-row>
        </template>
      </el-tree>
    </div>

    <!-- 父组件:xxx.sync=""的sync相当于双向绑定v-model,  @close发射update:xxx出去双向绑定 @refresh="getData"子传父刷新页面-->
    <AddDep ref="addDep" :current-pid="currentPid" :dialog-visible.sync="dialogVisible" @refresh="getData" />
  </div>
</template>
<script>
import { delDepartmentAPI, getDepartmentAPI } from '@/api/department'
import { arrayToTree } from '@/utils'
import AddDep from './AddDep.vue'

export default {
  name: 'Department',
  components: {
    AddDep
  },
  data() {
    return {
      treeData: [], // 部门节点-tree树形结构数据
      dialogVisible: false, // 对话框是否显示
      currentPid: 0 // 1.1当前部门id-父传子给弹出框
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      // 获取部门节点数据
      const res = await getDepartmentAPI()
      this.treeData = arrayToTree(res)
    },

    // 下拉菜单
    async command(command, id) {
      switch (command) {
        // 新增
        case 'add':
          this.dialogVisible = true // 显示对话框
          this.currentPid = id // 1.2存储当前部门id
          return

          // 编辑
        case 'edit':
          // 解决编辑字眼闪烁问题, 先加载完数据再打开对话框
          await this.$refs.addDep.getDepartmentDetail(id) // 调用子组件的方法发请求-回显
          this.dialogVisible = true
          return

          // 删除
        default:
          try {
            // 二次确认框
            await this.$confirm('此操作将永久删除该部门, 是否继续?', '温馨提示', { type: 'warning' })
            await delDepartmentAPI(id)
            this.$message.success('删除成功')
            this.getData()
          } catch (error) {
            console.log(error)
          }
          return
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container{
  margin: 0 10px;
  padding: 30px 140px;
}
</style>
